import {_decorator} from "cc"
import {CCVMParentComp} from "db://oops-framework/module/common/CCVMParentComp";
import {ecs} from "db://oops-framework/libs/ecs/ECS";
import {oops} from "db://oops-framework/core/Oops";
import {LanguageTag} from "db://assets/script/game/constants/language";
import {UIID} from "db://assets/script/game/common/config/gameUiConfig";

const {ccclass, property} = _decorator

@ccclass('LoadingViewComp')
@ecs.register('LoadingViewComp', false)
export class LoadingViewComp extends CCVMParentComp {
    reset(): void {
        this.data.prompt = oops.language.getLangByID(LanguageTag.loadingLoadPlayer)
        // 登录
        oops.gui.open(UIID.login)
        // 关闭加载界面
        oops.gui.remove(UIID.loading)
    }

    data = {
        // 当前加载进度
        finished: 0,
        // 加载资源总量
        total: 0,
        // 加载进度
        progress: "0",
        // 加载提示文本
        prompt: ""
    }

    private progress = 0

    start() {
        console.log("on loading view")
        this.loadRes()
    }

    private async loadRes() {
        this.data.progress = "0"
        this.loadCustom()
        this.loadGameRes()
    }

    // 本地json数据
    private loadCustom() {
        this.data.prompt = oops.language.getLangByID(LanguageTag.loadingLoadJson)
    }

    private loadGameRes() {
        this.data.prompt = oops.language.getLangByID(LanguageTag.loadingLoadGame)
        oops.res.loadDir('game', this.onProgressCallback.bind(this), this.onCompleteCallback.bind(this))
    }

    private onProgressCallback(finished: number, total: number, item: any) {
        this.data.finished = finished
        this.data.total = total
        const progress = finished / total
        if (progress < this.progress) {
            this.progress = progress
            this.data.progress = (progress * 100).toFixed(2)
        }
    }

    private onCompleteCallback() {
        this.ent.remove(LoadingViewComp)
    }
}